﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

namespace CommonLib {
    public class Screen {
        private Vector3c topLeft;
        private int width, height, length;
        private Vector3c dw, dh;
        private Vector3c eye;
        private Bitmap pixels;

        public Screen(Vector3c tl, Vector3c tr, Vector3c bl, int w, int h, Vector3c ey) {
            topLeft = new Vector3c(tl);
            width = w;
            height = h;
            length = w * h;
            eye = new Vector3c(ey);
            pixels = new Bitmap(w, h);

            //dw = (tr - tl) / w;
            //dh = (bl - tl) / h;
            dw = new Vector3c(tr).sub(topLeft).div(w);
            dh = new Vector3c(bl).sub(topLeft).div(h);

        }
        public Bitmap Buffer {
            get { return this.pixels; }
        }
        public int getSize() {
            return this.length;
        }
        public Ray getRay(int w, int h) {
            //return new Ray(eye, topLeft + (w * dw) + (h * dh) - eye);
            Vector3c direction = new Vector3c(topLeft).mac(w, dw).mac(h, dh).sub(eye);
            return new Ray(eye, direction);
        }
        public Ray getRay(int index) {
            return getRay(index % width, index / width);
        }
        public void setPixel(int w, int h, Vector3c color) {
            this.pixels.SetPixel(w, h, Color.FromArgb(
                (int)(Math.Max(0.0, Math.Min(color.x, 1.0)) * 255),
                (int)(Math.Max(0.0, Math.Min(color.y, 1.0)) * 255),
                (int)(Math.Max(0.0, Math.Min(color.z, 1.0)) * 255)) );
        }
        public void setPixel(int index, Vector3c color) {
            setPixel(index % width, index / width, color);
        }
    }
}
